package net.akcegaraz.tipleague.client.presenter;

import java.util.ArrayList;

import net.akcegaraz.tipleague.client.event.TicketCreatedEvent;
import net.akcegaraz.tipleague.client.event.TicketShownEvent;
import net.akcegaraz.tipleague.client.service.TipServiceAsync;
import net.akcegaraz.tipleague.shared.domain.Bet;
import net.akcegaraz.tipleague.shared.domain.Ticket;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class EditTicketPresenter implements Presenter {

    public interface Display {
	Widget asWidget();

	ArrayList<String> getBets();

	HasClickHandlers getCreateButton();

	HasClickHandlers getListButton();

	HasValue<String> getPlayerName();
    }

    private final TipServiceAsync rpcService;
    private final HandlerManager eventBus;
    private final Display display;
    private final Ticket ticket;

    public EditTicketPresenter(TipServiceAsync rpcService,
	    HandlerManager eventBus, Display display) {
	this.rpcService = rpcService;
	this.eventBus = eventBus;
	this.display = display;
	ticket = new Ticket();
	bind();
    }

    public void go(HasWidgets container) {
	container.clear();
	container.add(display.asWidget());
    }

    private void bind() {
	display.getCreateButton().addClickHandler(new ClickHandler() {
	    public void onClick(ClickEvent event) {
		doCreate();
	    }

	});
	display.getListButton().addClickHandler(new ClickHandler() {
	    public void onClick(ClickEvent event) {
		eventBus.fireEvent(new TicketShownEvent());
	    }

	});
    }

    private void doCreate() {
	ticket.getPlayer().setName(display.getPlayerName().getValue());
	for (String betValue : display.getBets()) {
	    Bet bet = new Bet();
	    bet.setBet(betValue);
	    ticket.getBets().add(bet);
	}
	System.out.println(ticket.getPlayer().getName() + " - "
		+ ticket.getBets().size());

	rpcService.addTicket(ticket, new AsyncCallback<Ticket>() {

	    public void onFailure(Throwable arg0) {
		Window.alert("Error updating ticket");
	    }

	    public void onSuccess(Ticket result) {
		eventBus.fireEvent(new TicketCreatedEvent(result));
	    }
	});
    }

}
